<template>
  <div class="app-container">
    <el-row :gutter="10">
      <el-col :span="5">
        <el-card>
          <avue-tree
            :option="treeOption"
            :data="treeData"
            @node-click="nodeClick"
          >
            <span
              class="el-tree-node__label showname"
              slot-scope="{ node }"
              :title="(node || {}).label"
            >
              {{ (node || {}).label }}
            </span>
          </avue-tree>
        </el-card>
      </el-col>
      <el-col :span="19">
        <avue-crud
          :option="option"
          :data="data"
          ref="user_crud"
          :table-loading="loading"
          :page.sync="page"
          @on-load="onLoad"
          @row-save="rowSave"
          @row-update="rowUpdate"
          @current-change="currentChange"
          @row-del="rowDel"
          @selection-change="selectionChange"
          @row-click="userRowClick"
          @search-change="searchChange"
          @search-reset="resetChange"
          :beforeOpen="beforeOpen"
        >
          <template slot="menuLeft">
            <el-button
              type="info"
              size="small"
              plain
              icon="el-icon-user"
              @click="handleGrant"
            >角色配置</el-button>
          </template>
          <template
            slot="menu"
            slot-scope="scope"
          >
            <el-button
              size="small"
              type="text"
              v-if="scope.row.userType == '1'"
              @click.stop="openCode(scope.row)"
              icon="el-icon-thumb"
            >邀请码</el-button>
          </template>
        </avue-crud>
      </el-col>
    </el-row>

    <el-dialog
      title="用户角色配置"
      class="avue-dialog"
      :visible.sync="roleBox"
      width="55%"
    >
      <avue-crud
        :option="roleOption"
        :table-loading="roleLoading"
        :data="roleData"
        ref="role_crud"
        v-model="roleForm"
        @selection-change="roleSelectionChange"
        @row-click="roleRowClick"
        :page.sync="rolePage"
        @on-load="onRoleLoad"
      >
      </avue-crud>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="cancel">取 消</el-button>
        <el-button
          type="primary"
          @click="submit"
        >确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      :title="userName+'的邀请码'"
      custom-class="code-dialog"
      center
      width="30%"
      :visible.sync="codeBox"
      @opened="ShowQRCode()"
    >
      <div class="userQrCode">
        <p>邀请码：{{caCode}}</p>
        <div id="userqrcode"></div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addUser,
  addCaUser,
  upUser,
  upCaUser,
  getUser,
  delUser,
  roleList,
  getRole,
  dRole,
  getOrg,
  getField,
  getCaCode,
} from '@/api/user.js'
import { addXml, getCert } from '@/api/login.js'
import QRCode from 'qrcodejs2'

export default {
  data() {
    return {
      userName: '',
      codeBox: false,
      caCode: '',
      authCode: '',
      /* 角色配置弹窗 */
      roleBox: false,
      roleLoading: false,
      roleForm: {},
      rolePage: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      /* 已选中角色 */
      roleSelectionList: [],
      roleData: [],
      roleOption: {
        headerAlign: 'center',
        align: 'center',
        dialogDrag: false,
        border: true,
        index: true,
        indexLabel: '序号',
        indexWidth: 100,
        addBtn: false,
        editBtn: false,
        delBtn: false,
        menu: false,
        selection: true,
        reserveSelection: true,
        column: [
          {
            label: '角色名称',
            prop: 'roleName',
          },
          /* {
                            label: '角色排序',
                            prop: 'roleOrder',
                            type: 'number',
                            value: 0,
                            width: 80
                        },
                        {
                            label: '是否有效',
                            prop: 'roleIsvalid',
                            type: 'select',
                            dicData: [{
                                label: '无效',
                                value: false
                            }, {
                                label: '有效',
                                value: true
                            }]
                        }, */
          {
            label: '描述',
            prop: 'roleDesc',
          },
        ],
      },

      /* 表格系列 */
      loading: false,
      /* 分页 */
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
        text: '',
        code: '',
        background: false,
      },
      /* 已选用户数组数据 */
      selectionList: [],
      /* 权限数据list */
      list: [],
      defaultObj: [],
      data: [],
      searchList: {},
      option: {
        headerAlign: 'center',
        dialogMenuPosition:'center',
        align: 'center',
        addBtnText: '新增用户',
        border: true,
        index: true,
        indexLabel: '序号',
        indexWidth: 100,
        card: true,
        tree: true,
        viewBtn: true,
        selection: true,
        dialogDrag: false,
        menuWidth: 250,
        menuFixed: 'right',
        searchLabelWidth: '25%',
        searchSpan: 6,
        searchMenuSpan: 4,
        column: [
          {
            label: '登录名',
            prop: 'loginName',
            search: true,
            searchPlaceholder: '请输入登录名',
            rules: [
              { required: true, message: '请输入登录名', trigger: 'blur' },
            ],
          },
          {
            label: '中文名',
            prop: 'userName',
            overHidden: true,
            rules: [
              { required: true, message: '请输入中文名', trigger: 'blur' },
            ],
          },
          {
            label: '密码',
            prop: 'loginPass',
            type: 'password',
            hide: true,
            viewDisplay: false,
            rules: [{ required: true, message: '请输入密码', trigger: 'blur' }],
          },
          {
            label: '确认密码',
            prop: 'passwdConfirm',
            type: 'password',
            hide: true,
            viewDisplay: false,
            /* rules: [
                                {required: true,validator:validatePass2,trigger: "blur"},
                            ], */
            //editDisplay: false,
          },
          {
            label: '员工号',
            prop: 'eid',
            overHidden: true,
            rules: [
              { required: true, message: '请输入员工号', trigger: 'blur' },
            ],
          },
          {
            label: '用户类型',
            prop: 'userType',
            type: 'select',
            rules: [
              { required: true, message: '请选择用户类型', trigger: 'change' },
            ],
            dicData: [],
            formatter: function (row, value) {
              //console.log('formatter',row,value)
              if (row.__ob__.dep.subs[0] && row.__ob__.dep.subs[0].vm && row.__ob__.dep.subs[0].vm.option) {
                if (row.userType !== '1') {
                  row.__ob__.dep.subs[0].vm.option.column[6].addDisplay = false
                  row.__ob__.dep.subs[0].vm.option.column[6].editDisplay = false
                  row.__ob__.dep.subs[0].vm.option.column[6].viewDisplay = false
                  row.__ob__.dep.subs[0].vm.option.column[7].addDisplay = false
                  row.__ob__.dep.subs[0].vm.option.column[7].editDisplay = false
                  row.__ob__.dep.subs[0].vm.option.column[7].viewDisplay = false
                } else {
                  row.__ob__.dep.subs[0].vm.option.column[6].addDisplay = true
                  row.__ob__.dep.subs[0].vm.option.column[6].editDisplay = true
                  row.__ob__.dep.subs[0].vm.option.column[6].viewDisplay = true
                  row.__ob__.dep.subs[0].vm.option.column[7].addDisplay = true
                  row.__ob__.dep.subs[0].vm.option.column[7].editDisplay = true
                  row.__ob__.dep.subs[0].vm.option.column[7].viewDisplay = true
                }
              }
              let label = row.__ob__.dep.subs[0] && row.__ob__.dep.subs[0].vm ? row.__ob__.dep.subs[0].vm.option.column[5].dicData.filter(
                  (item) => item.value == value
                ) : '';
              return label.length > 0 ? label[0].label : value
            },
          },
          /* CA用户新增需要证件类型与证件号码 */
          {
            label: '证件类型',
            prop: 'idType',
            type: 'select',
            value: 'SF',
            hide: true,
            rules: [
              { required: true, message: '请选择证件类型', trigger: 'change' },
            ],
            dicData: [
              {
                label: '身份证',
                value: 'SF',
              },
            ],
          },
          {
            label: '证件号码',
            prop: 'idNumber',
            overHidden: true,
            hide: true,
            rules: [
              { required: true, message: '请输入证件号码', trigger: 'blur' },
            ],
          },
          /* {
                            label: '职位',
                            prop: 'post',
                            type: 'select',
                            overHidden: true,
                            dicData: []
                        }, */
          {
            label: '是否启用',
            prop: 'accountIsvalid',
            type: 'select',
            value: true,
            rules: [
              { required: true, message: '请选择是否启用', trigger: 'change' },
            ],
            dicData: [
              {
                label: '启用',
                value: true,
              },
              {
                label: '禁用',
                value: false,
              },
            ],
          },
          {
            label: '所属机构',
            prop: 'deptCode',
            type: 'tree',
            rules: [
              { required: true, message: '请选择所属机构', trigger: 'change' },
            ],
            defaultExpandAll: true,
            expandOnClickNode: false,
            overHidden: true,
            dicData: [
              {
                id: 'R',
                deptValue: '全部',
                children: [],
              },
            ],
            props: {
              label: 'deptValue',
              value: 'id',
              children: 'children',
            },
          },
          {
            label: '手机号码',
            prop: 'userPhone',
            rules: [
              { required: true, message: '请输入手机号码', trigger: 'blur' },
            ],
          },
          {
            label: '电子邮箱',
            overHidden: true,
            prop: 'userEmail',
            rules: [
              { required: true, message: '请输入电子邮箱', trigger: 'blur' },
            ],
          },
          /* {
                            label: '邀请码',
                            width: 160,
                            overHidden: true,
                            hide:true,
                            disabled:true,
                            prop: 'caCode',
                            addDisplay:false,
                            editDisplay:false,
                        }, */
          {
            label: '备注',
            type: 'textarea',
            prop: 'userDesc',
            span: 24,
          },
        ],
      },
      /* 树形tree系列 */
      treeData: [
        {
          value: '',
          id: '1111111',
          deptValue: '全部',
          children: [],
        },
      ],
      treeOption: {
        defaultExpandAll: false,
        addBtn: false,
        filterText: '输入关键字检索',
        defaultExpandedKeys: ['1111111'],
        props: {
          label: 'deptValue',
          value: 'id',
          children: 'children',
        },
      },
    }
  },
  mounted() {
    this.getTree()
  },
  methods: {
    beforeOpen(done, type) {
      let loginName = this.option.column[0]
      let passwdConfirm = this.option.column[3]
      if (type === 'add') {
        loginName.disabled = false
        passwdConfirm.rules = [
          { required: true, message: '请再次输入密码', trigger: 'blur' },
        ]
      } else {
        loginName.disabled = true
        passwdConfirm.rules = [
          { required: false, message: '请再次输入密码', trigger: 'blur' },
        ]
      }
      done()
    },
    // tree树形  method
    nodeClick(data) {
      if (data.id && data.id != '1111111') {
        this.page.code = data.id
      } else {
        this.page.code = ''
      }
      this.onLoad()
    },
    /* 树形DATA */
    async getTree() {
      const data = await getOrg({
        page: 1,
        size: 1000000,
      })
      this.treeData[0].children = data.data.records;
      const deptCodeIndex = this.option.column.findIndex(item => item.prop === 'deptCode')
      const userTypeIndex = this.option.column.findIndex(item => item.prop === 'userType')
      // let i = this.findArray(this.option.column, 'deptCode', 'prop')
      // let j = this.findArray(this.option.column, 'userType', 'prop')
      /* let z = this.findArray(this.option.column, 'post', 'prop'); */
      // console.log('j',j)
      // console.log('i',i)
      // console.log('deptCodeIndex',deptCodeIndex)
      // console.log('userTypeIndex',userTypeIndex)
      if (deptCodeIndex > 0) {
        this.option.column[deptCodeIndex].dicData[0].children = this.treeData[0].children
      }

      if (userTypeIndex > 0) {
        const yhdata = await this.$store.dispatch('asyncApi/getDict', {
          code: 'YHLX',
        })
       // console.log('yhdata',yhdata)
        this.option.column[userTypeIndex].dicData = yhdata
      }
      /* if (z > 0) {
                    const data = await this.$store.dispatch('asyncApi/getDict', {
                        code: 'POST'
                    });
                    this.option.column[z].dicData = data;
                } */
    },
    onLoad(page, params = {}) {
      /* if (page.layout) {
                    Object.assign(params, {
                        page: this.page.currentPage,
                        size: this.page.pageSize,
                        code: page.code
                    });
                } else {
                    page.loginName ? page['text'] = page.loginName : page['text'] = ''
                    Object.assign(params, page);
                } */
      let searchList = this.searchList
      Object.assign(params, {
        ...searchList,
        text: searchList.loginName,
        page: this.page.currentPage,
        size: this.page.pageSize,
        code: this.page.code,
      })

      this.loading = true
      getUser(params).then((data) => {
        this.loading = false
        this.data = data.data.records
        this.page.total = data.data.total
      })
    },

    /* 清空 */
    resetChange() {
      this.page.currentPage = 1
      this.page.pageSize = 10
      this.page.code = ''
      this.searchList = {}
      this.onLoad()
    },
    /* 搜索筛选 */
    searchChange(params, done) {
      done()
      this.page.currentPage = 1
      this.page.pageSize = 10
      this.page.code = ''
      this.searchList = {
        ...params,
      }
      this.onLoad()
    },
    /* 新增用户 */
    rowSave(row, done, loading) {
      delete row['$accountIsvalid']
      delete row['$deptCode']
      delete row['$idType']
      delete row['$userType']
      let { userType } = row
      if (userType !== '1') {
        addUser(row).then((data) => {
          if (data.status) {
            this.onLoad(this.page)
            this.$message({
              type: 'success',
              message: '操作成功!',
            })
            done()
          } else {
            this.$message.error(data.msg)
            loading()
          }
        })
      } else {
        addXml({ type: row }).then((res) => {
          getCert().then((data) => {
            let param = {
              addCa: res.data.data,
              cert: data,
            }
            addCaUser(param).then((response) => {
              if (response.status) {
                this.onLoad(this.page)
                this.$message({
                  type: 'success',
                  message: '操作成功!',
                })
                done()
              } else {
                this.$message.error(response.msg)
                loading()
              }
            })
          })
        })
      }
    },
    /* 修改用户 */
    rowUpdate(row, index, done, loading) {
      delete row.createTime
      delete row.updateTime
      delete row.joinTime
      delete row.lastLoginTime
      delete row.apikeyrefreshtime
      delete row['$accountIsvalid']
      delete row['$deptCode']
      delete row['$idType']
      delete row['$userType']
      let { userType } = row
      if (userType !== '1') {
        upUser(row).then((data) => {
          if (data.status) {
            this.onLoad(this.page)
            this.$message({
              type: 'success',
              message: '操作成功!',
            })
            done()
          } else {
            this.$message.error(data.msg)
            loading()
          }
        })
      } else {
        addXml({ type: row }).then((res) => {
          getCert().then((data) => {
            let param = {
              upCa: res.data.data,
              cert: data,
            }
            upCaUser(param).then((response) => {
              if (response.status) {
                this.onLoad(this.page)
                this.$message({
                  type: 'success',
                  message: '操作成功!',
                })
                done()
              } else {
                this.$message.error(response.msg)
                loading()
              }
            })
          })
        })
      }
    },

    /* 改变页码 */
    currentChange(currentPage) {
      this.page.currentPage = currentPage
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        delUser({
          id: row.id,
        }).then(() => {
          this.onLoad(this.page)
          this.$message({
            type: 'success',
            message: '操作成功!',
          })
        })
      })
    },
    /* 选中列表回调 */
    selectionChange(list) {
      this.selectionList = list
    },
    /* 用户 && 角色列表行点击row选中 */
    userRowClick(row) {
      this.data.map((item) => {
        if (item.id == row.id) {
          this.$refs.user_crud.toggleSelection()
          this.$refs.user_crud.toggleSelection([item])
        }
      })
    },
    roleRowClick(row) {
      this.roleData.map((item) => {
        if (item.id == row.id) {
          this.$refs.role_crud.toggleSelection()
          this.$refs.role_crud.toggleSelection([item])
        }
      })
    },
    /* 角色配置 */
    handleGrant() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至多一条数据')
        return
      } else if (this.selectionList.length > 1) {
        this.$message.warning('请选择至多一条数据')
        return
      } else {
        this.onRoleLoad()
      }
    },
    /* 取消分配 */
    cancel() {
      this.roleBox = false
      this.$refs.role_crud.toggleSelection()
      this.$refs.user_crud.toggleSelection()
    },
    /* 权限提交 */
    submit() {
      let form = {}
      if (this.roleSelectionList.length === 0) {
        form = {
          k: this.selectionList[0].loginName,
          v: '',
        }
      } else if (this.roleSelectionList.length > 1) {
        this.$message.warning('请选择至多一条数据')
        return
      } else {
        form = {
          k: this.selectionList[0].loginName,
          v: this.roleSelectionList[0].id,
        }
      }
      dRole(form).then((data) => {
        if (data.status) {
          this.$message.success(data.msg)
          this.roleBox = false
          this.roleSelectionList = []
          this.selectionList = []
          this.$refs.role_crud.toggleSelection()
          this.$refs.user_crud.toggleSelection()
        } else {
          this.$message.error(data.msg)
        }
      })
    },
    roleOpen() {
      let _this = this
      this.roleLoading = true
      roleList({
        k: _this.selectionList[0].loginName,
      }).then((data) => {
        if (data.status) {
          //_this.$refs.role_crud.toggleRowSelection()
          _this.roleLoading = false
          _this.$refs.role_crud.toggleSelection()
          _this.roleData.forEach((item) => {
            if (item.id == data.data[0]) {
              //_this.$refs.role_crud.toggleSelection([item]);
              _this.$refs.role_crud.toggleRowSelection(item, true)
            }
          })
        } else {
          _this.$message.error('系统错误,请稍候再试!')
        }
      })
    },
    /* 选中角色回调 */
    roleSelectionChange(list) {
      if (list.length <= 1) {
        this.roleSelectionList = list
      } else {
        this.$refs.role_crud.toggleSelection()
        this.$message.error('请选择单个角色分配!')
      }
    },
    /* 获取角色列表 */
    onRoleLoad() {
      let page = this.rolePage
      getRole({
        page: page.currentPage,
        size: page.pageSize,
      }).then((data) => {
        this.roleData = data.data.records
        this.rolePage.total = data.data.total
        this.roleBox = true
        this.roleOpen()
      })
    },
    /* 打开邀请码弹框 */
    openCode(row) {
      let { userName, caId } = row
      getCaCode({ caId }).then((res) => {
        if (res.status) {
          this.caCode = res.data.data.code
          this.userName = userName
          this.codeBox = true
          this.authCode = JSON.parse(res.data.data.authCode)
          this.$nextTick(() => {
            document.getElementById('userqrcode').innerHTML = ''
          })
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    ShowQRCode() {
      let windowWidth = document.documentElement.clientWidth
      let width = 300 * (windowWidth / 1920)
      let authCode = this.authCode
      let qrcodeCreater = new QRCode('userqrcode', {
        width: width,
        height: width,
        correctLevel: 3,
        text: JSON.stringify(authCode),
      })
      qrcodeCreater._el.title = ''
    },
  },
}
</script>

<style scoped="scoped" lang="scss">
/deep/ .el-form-item__label {
  text-align: right !important;
}
/deep/ .avue-crud__pagination {
  text-align: center;
}
/deep/ .avue-flow,
.avue-flow__node,
.avue-tree {
  height: calc(100vh - 120px);
}
/deep/ .code-dialog {
  border-radius: 10px;
}
.userQrCode {
  width: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;

  p {
    font-size: 24px;
    font-weight: bold;
  }

  /* 二维码获取 */
  #qrcode {
    display: block;
    width: 300px;
    height: 300px;
    margin: 70px auto 25px;
  }
}
.showname {
  width: 200px;
  overflow: hidden !important; // 溢出部分隐藏
  white-space: nowrap !important; //禁止自动换行
  text-overflow: ellipsis !important; // 使溢出部分以省略号显示
  display: block !important;
}
</style>
